package com.yohann.algorithm;

/**
 * <p>
 * 顺序二叉树演示
 * </p>
 *
 * @author Yohann
 * @since 2021/1/3 16:28
 */
public class ArraysBinaryTreeDemo {
    public static void main(String[] args) {
        int[] arr = new int[]{1, 2, 3, 4, 5, 6, 7};
        new ArraysBinaryTree(arr).preOrder();
    }
}

/**
 * 顺序二叉树
 */
class ArraysBinaryTree {
    private int[] arr;

    public ArraysBinaryTree(int[] arr) {
        this.arr = arr;
    }

    public void preOrder() {
        System.out.println("<======================>");
        this.preOrder(0);
        System.out.println("\n<======================>");
    }

    //数组下标
    private void preOrder(int index) {
        if (arr == null || arr.length == 0) {
            System.out.println("数组为空！");
        }

        //输出当前元素
        System.out.print(arr[index] + "\t");

        //向左递归
        if ((index * 2 + 1) < arr.length) {
            preOrder(2 * index + 1);
        }

        //向右递归
        if ((index * 2 + 2) < arr.length) {
            preOrder(2 * index + 2);
        }
    }
}